package cc.catface.api.global.exception;

import cc.catface.common.output.BizException;
import cc.catface.common.output.ErrorCode;
import cc.catface.common.output.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;

/**全局异常拦截*/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    @ResponseBody//自定义异常
    public ResultBody handleBizException(HttpServletRequest request, BizException e) {
        log.error("业务异常:{}", e.getMessage());
        return ResultBody.error(e.getCode(), e.getMessage());
    }

    /**空指针*/
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultBody handleNullException(HttpServletRequest request, NullPointerException e) {
        log.error("空异常:{}", e.toString());
        return ResultBody.error(ErrorCode.ERROR_NULL);
    }

    /**请求方法不匹配*/
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ResultBody handleHttpRequestMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        log.error("请求方法不匹配:{}", e.toString());
        return ResultBody.error(ErrorCode.ERROR_HTTP_REQUEST_METHOD_NOT_SUPPORTED);
    }

    /**请求参数错误*/
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public ResultBody handleHttpMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException e) {
        log.error("请求参数异常:{}", e.toString());
        return ResultBody.error(ErrorCode.ERROR_HTTP_MESSAGE_NOT_READABLE);
    }

    /**上传文件无文件错误*/
    @ExceptionHandler(value = MultipartException.class)
    @ResponseBody
    public ResultBody handleMultipartException(HttpServletRequest request, MultipartException e) {
        log.error("上传文件无文件异常:{}", e.toString());
        return ResultBody.error(e.toString());
    }

    /**其他异常*/
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBody handleException(HttpServletRequest request, Exception e) {
        log.error("未知异常:{}", e.toString());
        return ResultBody.error(ErrorCode.ERROR_INTERNAL);
    }
}
